package com.vvitt.kotlinhiltcarhome.net

import android.util.Log
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import com.dongnaoedu.carhome.ext.isConnectedNetwork
import com.vvitt.flowpractice.common.BASE_URL1
import com.vvitt.kotlinhiltcarhome.db.CarBrandDataBase
import com.vvitt.kotlinhiltcarhome.entity.CarBrandEntity
import com.vvitt.kotlinhiltcarhome.init.AppHelper

/**
 * @ClassName RemoteCarBrandMediator
 * @author please call me police uncel
 * @since 2023/5/25.
 * @email 110
 * @Version: V1.0.0
 * @desciption 远程网络数据请求的 Mediator(中介)
 **/

@OptIn(ExperimentalPagingApi::class)
class RemoteCarBrandMediator(
    private val api: CarBrandApi,
    private val dataBase: CarBrandDataBase,
): RemoteMediator<Int, CarBrandEntity>() {

    /**
     * @desciption 加载网络数据
     * @since 2023/5/25
     **/
    override suspend fun load(loadType: LoadType,
                              state: PagingState<Int, CarBrandEntity>): MediatorResult {

        try {
            //第一步，判断 LoadType，根据LoadType计算page（当前页）
            Log.e("vvitt", "loadType = ${loadType}")
            val pageKey = when(loadType){
                // 首次访问 或者调用 PagingDataAdapter.refresh()
                LoadType.REFRESH -> null
                // 在当前加载的数据集的开头加载数据时
                LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
                // 加载更多时触发
                LoadType.APPEND -> {
                    val lastItem: CarBrandEntity = state.lastItemOrNull() ?: return MediatorResult.Success(endOfPaginationReached = true)
                    lastItem.page
                }
            }

            // 无网络，加载本地数据
            if (!AppHelper.mContext.isConnectedNetwork()){
                return MediatorResult.Success(endOfPaginationReached = true)
            }

            //第二步，请求网络分页数据
            val page = pageKey ?: 0
            val result = api.fetchCarBrandList(
                page * state.config.pageSize,
                state.config.pageSize
            )

            val item = result.map {
                CarBrandEntity(
                    id = it.id,
                    name = it.name,
                    icon = "${BASE_URL1 + "images/" + it.icon}",
                    page = page + 1
                )
            }

            val endOfPaginationReached = result.isEmpty()
            //第三步，插入数据库。

            val carBrandDao = dataBase.carBrandDao()
            dataBase.withTransaction {
                if (loadType == LoadType.REFRESH){
                    carBrandDao.clearCarBrand()
                }
                carBrandDao.insertCarBrand(item)
            }

            return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
        } catch (e: Exception) {
            e.printStackTrace()
            return MediatorResult.Error(e)
        }

    }


}


